package com.delay.queue.delayedqueue.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;

/**
 * @author gxing
 * @desc
 * @date 2021/3/22
 */
@Component
public class MessageProduce {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendDelayMessage(String msg) throws IOException {
        ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory();
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .expiration("6000") //过期时间 6 秒,单位毫秒
                .build();
        channel.basicPublish(RabbitMQConfig.DELAY_EXCHANGE_NAME, RabbitMQConfig.DELAY_MESSAGE_ROUTE_KEY, properties, msg.getBytes());
//        rabbitTemplate.convertAndSend(RabbitMQConfig.DELAY_EXCHANGE_NAME, RabbitMQConfig.DELAY_MESSAGE_ROUTE_KEY, msg);
    }

    public void xDelayedMessage(String msg) throws IOException {

        // channel.basicPublish
/*
        Channel channel = rabbitTemplate.getConnectionFactory().createConnection().createChannel(false);;
        HashMap<String, Object> headers = new HashMap<>();
        headers.put("x-delay", 5000);
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().headers(headers).build();
        channel.basicPublish(RabbitMQConfig.X_DELAYED_EXCHANGE_NAME, RabbitMQConfig.X_DELAYED_ROUTE_KEY, props, msg.getBytes(Charset.defaultCharset()));
*/

        // rabbitTemplate.convertAndSend
        rabbitTemplate.convertAndSend(RabbitMQConfig.X_DELAYED_EXCHANGE_NAME, RabbitMQConfig.X_DELAYED_ROUTE_KEY, msg, message -> {
            // 下面两都效果一样
            message.getMessageProperties().setDelay(6000);
//            message.getMessageProperties().setHeader("x-delay", 5000);
            return message;
        });
    }

}
